package com.chenyue.cm.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.user.domain.JdGoodsSku;
import com.chenyue.cm.user.domain.JdGoodsSkuExample;
import com.chenyue.cm.user.domain.JdGoodsSpu;
import com.chenyue.cm.user.service.JdGoodsSkuService;
import com.chenyue.cm.user.service.JdGoodsSpuService;
import com.chenyue.cm.user.service.JdGoodsStockLogService;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
* @author chenyue-cm
* @date 2024-03-01
*/
@RestController
@RequestMapping("/jdGoodsSku")
public class JdGoodsSkuController {

    @Autowired
    private JdGoodsSkuService mGoodsSkuService;

    @Autowired
    private JdGoodsSpuService mGoodsSpuService;

    @Autowired
    private JdGoodsStockLogService mGoodsStockLogService;


    @RequestMapping("/getList")
    @ResponseBody
    public Success<PageVo<JdGoodsSku>> getList(HttpServletRequest request, HttpServletResponse response) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        PageVo<JdGoodsSku> result = mGoodsSkuService.getPageBean(pageInfo, JdGoodsSku.class);
        return Success.success(result);
    }


    /**
     * @param vo
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    @Log(value = "sku商品属性关联- 保存数据", type = "2", module = "2")
    public Success save(JdGoodsSku vo, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");

        if (id != null && id != "") {
            mGoodsSkuService.getBaseMapper().updateById(vo);
        } else {
            vo.setId(UUID.randomUUID().toString().replace("-", ""));
            mGoodsSkuService.save(vo);
        }

        return Success.success();
    }


    /**
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deleteByGoodId/{id}")
    @ResponseBody
    @Log(value = "sku商品属性关联- 根据id删除数据", type = "2", module = "2")
    public Success delete(@PathVariable String id, HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");

        JdGoodsSkuExample aExample = new JdGoodsSkuExample();
        aExample.createCriteria().andGoodsIdEqualTo(id);
        mGoodsSkuService.deleteByExample(aExample);

        return Success.success();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @Log(value = "sku商品属性关联- 删除多个数据", type = "2", module = "2")
    public Success delete(HttpServletRequest request, HttpServletResponse response, Model model) {
        response.setContentType("text/html;charset=utf-8");
        String ids = request.getParameter("ids");
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            mGoodsSkuService.deleteByPrimaryKey(idString);
        }
        return Success.success();
    }

    /**
     * 保存关联数据
     */
    @RequestMapping("/saveSkuInfo")
    @ResponseBody
    @Log(value = "sku商品属性关联- 保存关联数据", type = "2", module = "2")
    @Transactional
    public Success saveSkuInfo(HttpServletRequest request, HttpServletResponse response) {

        //更新spu 的属性信息
        String goodsId = request.getParameter("goodsId");
        System.out.println(goodsId);
        JdGoodsSpu a = mGoodsSpuService.selectByPrimaryKey(goodsId);
        String spuAttrInfo = request.getParameter("spuAttrInfo");
        System.out.println(spuAttrInfo);
        String skuInfoArray = request.getParameter("skuInfoArray");
        System.out.println(skuInfoArray);

            // 删除规格信息
            LambdaQueryWrapper<JdGoodsSku> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JdGoodsSku::getGoodsId,goodsId);
            mGoodsSkuService.remove(wrapper);
            List<JdGoodsSku> mGoodsSkuList = JSONObject.parseArray(skuInfoArray, JdGoodsSku.class);
            //单规格
            if (mGoodsSkuList.size() == 1) {
                spuAttrInfo = null;
            }
            //多规格
            for (JdGoodsSku mGoodsSku : mGoodsSkuList) {
                mGoodsSku.setId(UUID.randomUUID().toString().replace("-", ""));
                mGoodsSku.setCreateTime(DateUtils.getCurrentTime());
                mGoodsSkuService.save(mGoodsSku);
                mGoodsStockLogService.saveStockLog(mGoodsSku.getId(), 1, mGoodsSku.getSkuStock(), mGoodsSku.getSkuStock(), mGoodsSku.getSkuStock());
            }
            //保存规格字符串到商品表
            a.setUpdateUser(spuAttrInfo);
            mGoodsSpuService.updateById(a);


        return Success.success();
    }

    /**
     * 保存库存更新数据以及日志
     */
    @RequestMapping("/saveStockInfo")
    @ResponseBody
    @Log(value = "商品库存- 保存库存数据", type = "2", module = "2")
    @Transactional
    public Success saveStockInfo(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        String skuInfoArray = request.getParameter("skuInfoArray");
        //规格字符串转对象
        List<JdGoodsSku> mGoodsSkuList = JSONObject.parseArray(skuInfoArray, JdGoodsSku.class);

        try {
            for (JdGoodsSku mGoodsSku : mGoodsSkuList) {
                JdGoodsSku goodsSku = mGoodsSkuService.selectByPrimaryKey(mGoodsSku.getId());
                if (goodsSku != null) {
                    if (!goodsSku.getSkuStock().equals(mGoodsSku.getSkuStock()) || !goodsSku.getSkuWeight().equals(mGoodsSku.getSkuWeight())) {
                        mGoodsSku.setUpdateTime(DateUtils.getCurrentTime());
                        mGoodsSkuService.updateById(mGoodsSku);
                        mGoodsStockLogService.saveStockLog(mGoodsSku.getId(), 1, goodsSku.getSkuStock(), mGoodsSku.getSkuStock() - goodsSku.getSkuStock(), mGoodsSku.getSkuStock());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException();
        }

        return Success.success();
    }

    /**
     * 根据商品获取商品的sku
     */
    @RequestMapping("/getSkuInfoByGoodsId")
    @ResponseBody
    public Success getSkuInfoByGoodsId(HttpServletRequest request, HttpServletResponse response) {

        String goodsId = request.getParameter("goodsId");
        List<JdGoodsSku> mGoodsSkuByGoodsId = mGoodsSkuService.getMGoodsSkuByGoodsId(goodsId);
        return Success.success(mGoodsSkuByGoodsId);
    }

    /**
     * 根据商品获取商品的sku中最小价格
     */
    @RequestMapping("/getSkuMinPriceByGoodsId")
    @ResponseBody
    public Success getSkuMinPriceByGoodsId(HttpServletRequest request, HttpServletResponse response) {
        String goodsId = request.getParameter("goodsId");
        BigDecimal minPrice = mGoodsSkuService.getSkuMinPriceByGoodsId(goodsId);
        return Success.success(minPrice);
    }


}
